<script setup name="MeltPropertiesTools">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { calculateSurfaceTension, calculateViscosity } from '@/api/product/mdtk'

const { t } = useI18n()

const props = defineProps({
	type: String, // 类型
	elementalGroup: String, // 组元素
	selectedElements: Array, // 选中元素
})

const result = ref(null)
const formRef = ref(null)
const isLoading = ref(false)

// 表单数据
const form = ref({
	composition: [], // 元素成分
	system: '', // 元素组分
	system_type: '', // 算法类型
	temperature: 1573, // 温度
})

const elements = computed(() => {
	const group = props.elementalGroup || ''
	return typeof group === 'string'
		? group
				.split('-')
				.filter(Boolean) // 过滤空字符串
				.map((item, index) => ({
					props: `element-${item.toLowerCase()}`, // 更语义化的键名
					label: item,
				}))
		: []
})
// 校验规则
const validationRules = computed(() => ({
	temperature: [
		{
			required: true,
			message: '请输入温度',
			trigger: 'blur',
		},
		{
			pattern: /^\d+(\.\d{1,4})?$/,
			message: '温度必须为数字且最多四位小数',
			trigger: 'blur',
		},
	],
	...elements.value.reduce((rules, item, index) => {
		rules[item.props] = [
			{
				required: true,
				message: `${item.label}组分不能为空`,
				trigger: 'blur',
			},
			{
				validator: (rule, value, callback) => {
					const sum = form.value.composition.reduce((a, b) => a + b, 0)
					if (Math.abs(sum - 1) > 0.0001) {
						// 允许浮点数误差
						callback(
							new Error(`所有组分之和必须等于1（当前: ${sum.toFixed(4)}）`)
						)
					} else {
						callback()
					}
				},
				trigger: 'blur',
			},
		]
		return rules
	}, {}),
}))

// 在watch中替换原有逻辑
watch(
	() => elements.value,
	(val) => {
		// 初始化默认值（二元组/三元组）
		if (val.length === 2) {
			form.value.composition = [0.5, 0.5]
			form.value.system_type = 'binary'
		} else if (val.length === 3) {
			form.value.composition = [0.33, 0.33, 0.34]
			form.value.system_type = 'ternary'
		}
	},
	{ immediate: true }
)

// 动态计算组分值的核心方法
const updateComposition = (index, newValue) => {
	const precision = 4 // 小数精度
	const minValue = 0.0001 // 最小值保护

	// 处理二元组
	if (elements.value.length === 2) {
		const otherIndex = index === 0 ? 1 : 0
		const remaining = 1 - newValue

		// 边界保护
		if (remaining < minValue) {
			form.value.composition[index] = 1 - minValue
			form.value.composition[otherIndex] = minValue
		} else if (remaining > 1 - minValue) {
			form.value.composition[index] = minValue
			form.value.composition[otherIndex] = 1 - minValue
		} else {
			form.value.composition[otherIndex] = parseFloat(
				remaining.toFixed(precision)
			)
		}
	}

	// 处理三元组
	else if (elements.value.length === 3) {
		const [a, b] =
			index === 0
				? [newValue, form.value.composition[1]]
				: [form.value.composition[0], newValue]

		let sum = a + b
		let remaining = 1 - sum

		// 边界保护
		if (remaining < minValue) {
			const adjust = (1 - minValue - sum) / 2
			form.value.composition[0] = parseFloat((a + adjust).toFixed(precision))
			form.value.composition[1] = parseFloat((b + adjust).toFixed(precision))
			form.value.composition[2] = minValue
		} else {
			form.value.composition[2] = parseFloat(remaining.toFixed(precision))
		}
	}
}

const submitForm = async () => {
	try {
		const valid = await formRef.value.validate()
		if (valid) {
			isLoading.value = true
			form.value.system = props.elementalGroup
				.split('-')
				.join('_')
				.split('.')[0]
			const api =
				props.type === '表面张力计算'
					? calculateSurfaceTension
					: calculateViscosity

			result.value = await api(form.value)
			isLoading.value = false
			ElMessage.success('计算成功')
		} else {
			ElMessage.error('请完成必填项')
		}
	} catch (error) {
		isLoading.value = false
	}
}
</script>

<template>
	<div class="component-form">
		<el-form
			ref="formRef"
			:model="form"
			:rules="validationRules"
			label-width="100px"
		>
			<!-- 温度输入 -->
			<el-form-item
				:label="t('mainPage.components.meltProperties.temperature')"
				prop="temperature"
			>
				<div class="tempStyle">
					<el-input-number
						v-model="form.temperature"
						:precision="2"
						:min="298.15"
						:max="2000"
						placeholder="1573"
						:controls="false"
						class="inputNumber"
					/>
					<span class="text">温度(K)：289.15K ～ 2000K</span>
				</div>
			</el-form-item>

			<el-form-item
				v-for="(item, index) in elements"
				:key="index"
				:prop="`composition[${index}]`"
				:label="item.label + '组分'"
				:rules="validationRules[item.props]"
			>
				<el-input-number
					v-model="form.composition[index]"
					@input="(val) => updateComposition(index, val)"
					placeholder="请输入0~1的小数"
					:precision="4"
					:min="0.0001"
					:max="1"
					:controls="false"
					:readonly="index === elements.length - 1"
					class="inputNumber"
				/>
			</el-form-item>
		</el-form>

		<div class="form-actions">
			<el-button
				type="primary"
				size="small"
				:loading="isLoading"
				@click="submitForm"
			>
				{{ t('mainPage.components.meltProperties.startCalculation') }}
			</el-button>
		</div>
		<!-- 结果卡片区域 -->
		<div v-if="result" class="calculator-result-card">
			<h3>{{ t('mainPage.components.meltProperties.resultMessage') }}</h3>
			<div class="result-value">{{ Number(result.result).toFixed(3) }}</div>
			<div class="result-unit">
				{{
					props.currentCalculationType === '表面张力计算'
						? t('mainPage.components.meltProperties.units.surfaceTension')
						: t('mainPage.components.meltProperties.units.viscosity')
				}}
			</div>
		</div>
	</div>
</template>

<style scoped lang="scss">
.form-actions {
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 10px;

	:deep(.el-button) {
		flex: 1;
	}
}

// 表单验证错误状态
:deep(.el-form-item) {
	margin-bottom: 20px !important;
	.el-form-item__error {
		display: block !important;
	}
}

.calculator-result-card {
	background: var(--theme-gradient-result);
	border-radius: 16px;
	padding: 30px;
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	border: 1px solid var(--theme-accent);

	margin: 24px 0 0 0;
	box-shadow: var(--theme-card-shadow);

	h3 {
		color: var(--theme-content-title);
		margin-bottom: 15px;
		font-size: 1.3rem;
	}

	.result-value {
		font-size: 2.5rem;
		font-weight: 700;
		color: var(--theme-accent);
		margin: 15px 0;
		width: 200px;
		word-break: break-all;
		white-space: normal;
		line-height: 1.2;
		text-align: center;
	}

	.result-unit {
		font-size: 1.1rem;
		color: var(--theme-content-text-muted);
	}
}

:deep(.inputNumber) {
	width: 100% !important;
	.el-input__wrapper {
		padding: 1px 11px !important;
		.el-input__inner {
			text-align: left;
		}
	}
}

.tempStyle {
	position: relative;
	width: 100%;
	.text {
		position: absolute;
		font-size: 0.75rem;
		bottom: -26.7px;
		right: 0;
	}
}
</style>

<style>
@import url('@/styles/element-plus/form.scss');
</style>
